package com.hengpeng.itfin.service.activity.impl;

import java.util.Date;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.service.activity.RedPacketService;
import com.hengpeng.itfin.service.impl.BaseServiceImpl;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.AccountType;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.TransferRequest;
import com.hengpeng.itfinbase.message.partner.TransferResponse;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.RedPacketPayLog;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.itfinbase.persist.SystemLog.LogType;
import com.hengpeng.itfinbase.persist.UserInfo;

@Lazy
@Service
public class RedPacketServiceImpl extends BaseServiceImpl implements RedPacketService {

    private static final String MDT000001 = "MDT000001";// 托管子账户名

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int updateStatus(long id, RewardRedPacketStatus oldStatus, RewardRedPacketStatus newStatus, Date updateTime) {
        return serviceFactory.getDaoFactory().getRedPacketDao().updateStatus(id, oldStatus, newStatus, updateTime);
    }

    @Override
    public ResponseMessage investUseRedPacket(Long redPacketId) {
        ResponseMessage response = new ResponseMessage();
        int j = serviceFactory.getRedPacketService().updateStatus(redPacketId, RewardRedPacketStatus.CANUSE,
                RewardRedPacketStatus.USEED, new Date());
        if (j <= 0) {
            response.setRespCode(RespCodeConstants.CommonCode.TRANS_SUC);
            response.setRespDesc("该红包已使用或已过期");
        }
        return response;

    }

    @Override
    public void investRedPacketTransfer(Long redPacketId, InvestInfo investInfo) {
        RewardRedpacket redpacket = serviceFactory.getDaoFactory().getRedPacketDao().get(investInfo.getRedPacketId());
        if (RewardRedPacketStatus.USEED.equals(redpacket.getStatus())) {
            // 入账账户
            Account inAccount = serviceFactory.getDaoFactory().getAccountDao()
                    .getAccountByUserId(investInfo.getInvestUserId());
            // 出账用户
            UserInfo outUser = serviceFactory.getDaoFactory().getUserInfoDao()
                    .get(Long.parseLong(SystemConfigUtil.getConfigValue(SystemConfigConstants.PARTNER_USERID)));
            // 出账账户
            Account outAccount = serviceFactory.getDaoFactory().getAccountDao()
                    .getAccountByUserIdAndSub(outUser.getId(), MDT000001);
            /**
             * 调用划账接口
             */
            TransferRequest transferRequest = new TransferRequest();
            transferRequest.setOutType(AccountType.PLATFORM);// 固定出账户只能是平台账户
            transferRequest.setOutUserId(outUser.getId());
            transferRequest.setOutCustId(outAccount.getTrustAccountId());
            transferRequest.setOutAcctId(outAccount.getSubAccountId());
            transferRequest.setInType(AccountType.PERSONAL);
            transferRequest.setInUserId(investInfo.getInvestUserId());
            transferRequest.setInCustId(inAccount.getTrustAccountId());
            transferRequest.setInAcctId(inAccount.getSubAccountId());
            transferRequest.setTransAmt(MoneyUtil.convertFenToYuan(redpacket.getMoney()));
            transferRequest.setPartnerTransType(PartnerTransType.Transfer);
            transferRequest.setBgRetUrl(service_notify_url);
            transferRequest.setRetUrl(page_return_url);
            transferRequest.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
            transferRequest.setReferenceId(redpacket.getId().toString());
            transferRequest.setMerPriv("REDPACKETBACK");// 红包划账
            TransferResponse transferResponse = (TransferResponse) serviceFactory.getPartnerService().request(
                    transferRequest);
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(transferResponse.getRespCode())) {// 成功生成红包使用记录
                /**
                 * 生成红包使用记录
                 */
                RedPacketPayLog redPacketPayLog = new RedPacketPayLog();
                redPacketPayLog.setRedPacketId(redpacket.getId());
                redPacketPayLog.setCreateTime(new Date());
                redPacketPayLog.setMoney(redpacket.getMoney());
                redPacketPayLog.setReferenceId(transferResponse.getOrdId());
                redPacketPayLog.setRemnantMoney(0l);
                redPacketPayLog.setTransTime(new Date());
                redPacketPayLog.setTransType(TransType.INVEST_REDPACKET_BACK);
                redPacketPayLog.setUpdateTime(new Date());
                redPacketPayLog = serviceFactory.getPersistService().save(redPacketPayLog);
                if (redPacketPayLog.getId() == null) {
                    serviceFactory.getSystemLogService().addLog(investInfo.getBorrowInfoId().toString(),
                            investInfo.getId().toString(), LogType.INVEST_EXCEPTION,
                            "投标成功,使用红包成功，划账成功,生成红包使用记录失败,红包ID[" + investInfo.getRedPacketId() + "]");
                }
            } else {
                /**
                 * 回退红包状态
                 */
                int l = serviceFactory.getRedPacketService().updateStatus(redpacket.getId(),
                        RewardRedPacketStatus.USEED, RewardRedPacketStatus.CANUSE, new Date());
                if (l <= 0) {
                    serviceFactory.getSystemLogService().addLog(investInfo.getBorrowInfoId().toString(),
                            investInfo.getId().toString(), LogType.INVEST_EXCEPTION,
                            "投标成功,使用红包失败，回退红包状态失败,数据库更新状态失败,红包ID[" + investInfo.getRedPacketId() + "]");
                }
            }
        } else {
            serviceFactory.getSystemLogService().addLog(investInfo.getBorrowInfoId().toString(),
                    investInfo.getId().toString(), LogType.INVEST_EXCEPTION,
                    "投标成功,使用红包异常,红包状态应为[USED],当前状态为["+redpacket.getStatus()+"],红包ID[" + investInfo.getRedPacketId() + "]");
        }
    }

}
